package com.runda.sec;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.bbjob.sec.util.JwtTokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.runda.entity.JwtUser;

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    Logger logger = LoggerFactory.getLogger(getClass());
    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        // 从输入流中获取到登录的信息
        try {
            Map<String, String> userMap = new ObjectMapper().readValue(request.getInputStream(), HashMap.class);
            return authenticationManager.authenticate(new CustomUsernamePasswordAuthenticationToken(
                    userMap.get("username"), userMap.get("password"), new ArrayList<>(), userMap.get("oriCode")));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BadCredentialsException("错误的登录请求数据。。。");
        }
    }

    // 成功验证后调用的方法
    // 如果验证成功，就生成token并返回

    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException {

        // 查看源代码会发现调用getPrincipal()方法会返回一个实现了`UserDetails`接口的对象
        // 所以就是JwtUser啦
        JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
        if (logger.isDebugEnabled()) {
            logger.debug("jwtUser:" + jwtUser.toString());
        }

        String token = JwtTokenUtils.createToken(jwtUser.getUsername(), false);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的格式应该是 `Bearer token`
        response.setHeader(JwtTokenUtils.TOKEN_HEADER, JwtTokenUtils.TOKEN_PREFIX + token);
        response.setHeader("Access-Control-Expose-Headers", JwtTokenUtils.TOKEN_HEADER);
    }

    // 这是验证失败时候调用的方法

    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException failed) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("登录失败: " + failed.getMessage());
    }

}
